package org.holynite.fieldmanage.managed.controller

import org.holynite.fieldmanage.ejbs.CustomerTypeManagement
import org.holynite.fieldmanage.entities.CustomerType
import org.holynite.fieldmanage.managed.model.CustomerTypeFormBean
import org.holynite.fieldmanage.managed.model.CustomerTypesBean
import org.holynite.fieldmanage.managed.support.ChargeTypeBean
import org.holynite.fieldmanage.managed.support.UsableTimeBean
import org.holynite.fieldmanage.types.ChargeType
import org.holynite.fieldmanage.types.UsableTime
import org.holynite.fieldmanage.utils.LocaleString

import javax.annotation.PostConstruct
import javax.ejb.EJB
import javax.faces.bean.ManagedBean
import javax.faces.bean.ManagedProperty
import javax.faces.bean.RequestScoped
import javax.faces.bean.ViewScoped
import javax.faces.el.EvaluationException
import javax.faces.event.ValueChangeEvent
import javax.faces.model.SelectItem
import javax.inject.Inject

/**
 * Created by midnite on 15/1/18.
 */
@ManagedBean
@ViewScoped
class CustomerTypeBean {

	@EJB(beanName = "customerTypeControl")
	CustomerTypeManagement ctService
    @ManagedProperty("#{customerTypeFormBean}")
    CustomerTypeFormBean ctForm
    @ManagedProperty("#{customerTypesBean}")
    CustomerTypesBean ctBean
    @ManagedProperty("#{chargeTypeBean}")
    ChargeTypeBean chargeBean
    @ManagedProperty("#{usableTimeBean}")
    UsableTimeBean utBean
	@Inject
	LocaleString locale

	CustomerTypeBean() {
	}

	def searchTypes() {
		ctForm.clearForm()
        ctBean.reloadCustomerTypes(ctForm.searchKeyword)
		null
	}

	def saveCustomerType() {
		if (ctForm.addMode) {
			def newType = new CustomerType(
				customerTypeName: ctForm.typeName,
				precharged: ctForm.precharged,
				discount: ctForm.discount,
				multipleChargeAsSingle: ctForm.multipleAllowed,
				chargeType: chargeBean.findByCodeSign(ctForm.selectedCharge),
				usables: utBean.findByCodeSign(ctForm.selectedUsable)
			)
			ctService.addType(newType)
		} else {
			try {
				def selectedType = ctBean.findCustomerType(ctForm.selectedType)
				selectedType.customerTypeName = ctForm.typeName
				selectedType.precharged = ctForm.precharged
				selectedType.discount = ctForm.discount
				selectedType.multipleChargeAsSingle = ctForm.multipleAllowed
				selectedType.chargeType = chargeBean.findByCodeSign(ctForm.selectedCharge)
				selectedType.usables = utBean.findByCodeSign(ctForm.selectedUsable)
				ctService.saveType(selectedType)
			} catch (NullPointerException e) {
				throw new Exception(locale.fetch("custypeManageExceptionNoSelection"))
			}
		}
		ctForm.clearForm()
		ctBean.reloadCustomerTypes(ctForm.searchKeyword)
		null
	}

    def deleteCustomerType() {
        if (ctForm.addMode) throw new Exception(locale.fetch("warningDeleteInNew"))
        ctService.removeType(ctForm.selectedType)
        ctBean.reloadCustomerTypes(ctForm.searchKeyword)
        ctForm.clearForm()
        null
    }
}
